package com.nowcoder.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.MailClient;
import com.nowcoder.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author szq
 * @create 2023-01-18 22:25
 * @description 用户服务
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, CommunityConstant, UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

//    @Autowired
//    private LoginTicketMapper loginTicketMapper;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Override
    public User findUserById(int id) {
        //User user = userMapper.selectById(id);
        // 优先从缓存中取值
        User user = getCache(id);
        // 取不到时，初始化缓存数据(从mysql取)
        if (user == null) {
            user = initCache(id);
        }
        return user;
    }

    /**
     * 优先从缓存中取值
     *
     * @param userId 用户id
     * @return 用户
     */
    @Override
    public User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 取不到时，初始化缓存数据
     *
     * @param userId 用户id
     * @return 用户
     */
    @Override
    public User initCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        User user = getById(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    /**
     * 数据变更时清除缓存数据
     *
     * @param userId 用户id
     */
    @Override
    public void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 注册结果信息
     */
    @Override
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        // 空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空！");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空！");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }
        // 验证账号
        User u = getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (u != null) {
            map.put("usernameMsg", "该账号已存在！");
            return map;
        }
        // 验证邮箱
        u = getOne(new QueryWrapper<User>().eq("email", user.getEmail()));
        if (u != null) {
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }

        /*
        注册账户
            1.设置salt加密(随机5位数加入密码)
            2.设置密码+salt
            3.设置随机数激活码
            4.设置status=0（未激活）,type=0（普通用户）,用户创建时间
            5.设置头像(动态)
              user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000))
        */
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);    // 普通用户
        user.setStatus(0);  // 未激活
        user.setActivationCode(CommunityUtil.generateUUID());   // 设置激活码
        user.setHeaderUrl(String.format("https://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        save(user);

        /*
        激活邮件
            1.创建Context对象
            2.通过context.setVariable(name,value)设置email和url，传给HTML
            3.templateEngine.process执行相应HTML
            4.发送邮件
        */
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        //http://localhost:8080/community/activation/101/code激活链接
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);
        return map;
    }

    /**
     * 处理激活请求
     *
     * @param userId 用户Id
     * @param code   激活码
     * @return 激活状态：成功、失败、重复激活
     */
    public int activation(int userId, String code) {
        User user = findUserById(userId);
        if (user.getStatus() == 1) {
            return ACTIVATION_REPEAT;   //重复激活
        } else if (user.getActivationCode().equals(code)) {
            update().setSql("status=1").eq("id", userId).update();  //更新状态
            clearCache(userId);         //清除缓存
            return ACTIVATION_SUCCESS;  //激活成功
        } else {
            return ACTIVATION_FAILURE;  //激活失败
        }
    }

    /**
     * 登录服务
     *
     * @param username      用户名
     * @param password      密码
     * @param expiredSecond 过期时间
     * @return 登录状态信息
     */
    @Override
    public Map<String, Object> login(String username, String password, long expiredSecond) {
        Map<String, Object> map = new HashMap<>();
        // 空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        // 验证账号
        User user = getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }
        // 验证状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }
        // 验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!password.equals(user.getPassword())) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }
        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setStatus(0);
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setExpired(new Date(System.currentTimeMillis() + 1000 * expiredSecond));
        // loginTicketMapper.insertLoginTicket(loginTicket);
        // 将登录凭证存到 Redis 中
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey, loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    /**
     * 退出登录
     *
     * @param ticket 凭证
     */
    @Override
    public void logout(String ticket) {
        //loginTicketMapper.updateStatus(ticket, 1);
        // Redis优化
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);// 更新状态 0-有效; 1-无效(已删除状态)
        redisTemplate.opsForValue().set(redisKey, loginTicket);
    }

    /**
     * @param ticket 查询登录凭证
     * @return 登录凭证
     */
    @Override
    public LoginTicket findLoginTicket(String ticket) {
        //return loginTicketMapper.selectByTicket(ticket);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 更新用户头像
     *
     * @param userId    用户Id
     * @param headerUrl 头像地址
     * @return 1表示更新成功，0表示更新失败
     */
    @Override
    public int updateHeader(int userId, String headerUrl) {
        boolean result = update().setSql("header_url = \"" + headerUrl + "\"").eq("id", userId).update();
        clearCache(userId); // 更新用户数据，删除缓存
        return result ? 1 : 0;
    }

    @Override
    public Map<String, Object> updatePassword(int userId, String oldPassword, String newPassword) {
        Map<String, Object> map = new HashMap<>();

        // 空值处理
        if (StringUtils.isBlank(oldPassword)) {
            map.put("oldPasswordMsg", "原密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(newPassword)) {
            map.put("newPasswordMsg", "新密码不能为空!");
            return map;
        }

        // 验证原密码
        User user = findUserById(userId);
        oldPassword = CommunityUtil.md5(oldPassword + user.getSalt());
        if (!user.getPassword().equals(oldPassword)) {
            map.put("oldPasswordMsg", "您输入的原密码错误！");
            return map;
        }
        // 原密码正确，更新密码
        newPassword = CommunityUtil.md5(newPassword + user.getSalt());
        boolean result = update().set("password", newPassword).eq("id", user.getId()).update();
        clearCache(userId);
        if (!result) {
            logger.error("密码更新失败");
        }
        return map;
    }



    @Override
    public User findUserByName(String username) {
        return getOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userMapper.findUserByUsername(username);
    }
}